package com.student.dao;



        import com.student.model.User;

        import java.sql.Connection;
        import java.sql.PreparedStatement;
        import java.sql.ResultSet;
        import java.sql.SQLException;

/**
 * 用户信息的数据库访问类
 *
 * @author 康娜的小肥腿
 */
public class UserDao {

    /**
     * 登录操作
     *
     * @param username
     * @param password
     * @return
     */
    public User login(String username, String password) {
        String sql = "select * from users where user_name=? and password=?";
        Connection conn = JdbcUtil.getConnection();
        PreparedStatement ps = null;
        ResultSet rs = null;
        try {
            // 4. 通过语句对象执行CRUD（增查改删），如果为查询则获得结果集java.sql.ResultSet
            ps = conn.prepareStatement(sql);
            // 执行预编译语句前必须设置占位符的值
            ps.setString(1,username);
            ps.setString(2,password);

            // 5. 执行查询号并且遍历查询结果集，如果是增删改则忽略此步骤
            rs = ps.executeQuery();
            while (rs.next()) {
                int userId = rs.getInt("user_id");
                String userName = rs.getString("user_name");
                String password1 = rs.getString("password");
                return new User(userId, userName, password1);
            }

        } catch (SQLException e) {
            System.err.println("登录失败." + e.getMessage());
        } finally {
            // 6. 关闭数据相关资源: Connection, Statement, ResultSet
            JdbcUtil.close(conn, ps, rs);
        }
        return null;
    }



    public static void main(String[] args) {
        // 测试
        System.out.println(new UserDao().login("james", "zhang"));
    }
}
